// store/modules/user.ts
import { defineStore } from "pinia";
import type { UserState } from "../../types/user";

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    isLoggedIn: false,
    token: null,
    tokenExpiresAt: null,
    refreshToken: null,
    userProfile: null,
  }),

  getters: {
    currentUser: (state) => state.userProfile,
    authToken: (state) => state.token,
    isAuthenticated: (state) => state.isLoggedIn,
  },

  actions: {
    loginSuccess(loginResponse: any) {
      this.$patch({
        token: loginResponse.token,
        tokenExpiresAt: loginResponse.tokenExpiresAt,
        refreshToken: loginResponse.refreshToken,
        isLoggedIn: true,
        userProfile: loginResponse.userProfile,
      });

      // 存储到本地
      localStorage.setItem("authToken", loginResponse.token);
      localStorage.setItem(
        "userProfile",
        JSON.stringify(loginResponse.userProfile)
      );
    },

    logout() {
      // 重置状态
      this.$reset();

      // 清理本地存储
      localStorage.removeItem("authToken");
      localStorage.removeItem("userProfile");
    },

    // 可选的初始化方法
    initializeFromLocalStorage() {
      const token = localStorage.getItem("authToken");
      const profileJson = localStorage.getItem("userProfile");

      if (token && profileJson) {
        try {
          const userProfile = JSON.parse(profileJson);
          this.$patch({
            token,
            isLoggedIn: true,
            userProfile,
          });
        } catch (e) {
          console.error("Failed to initialize user from local storage", e);
        }
      }
    },
  },
});
